package com.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.common.utils.DateUtil;
import com.common.utils.Result;
import com.entity.Card;
import com.entity.Label;
import com.entity.TaskRecord;
import com.entity.TaskStore;
import com.mapper.TaskStoreMapper;
import com.query.TaskStoreQuery;
import com.service.CardService;
import com.service.LabelService;
import com.service.TaskRecordService;
import com.service.TaskStoreService;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author wty
 * @since 2021-01-12
 */
@Service
public class TaskStoreServiceImpl extends ServiceImpl<TaskStoreMapper, TaskStore> implements TaskStoreService {

//    static String nowTime= DateFormatUtils.format(new Date(), "yyyy-MM-dd");;//今天的时间

    @Autowired
    private LabelService labelService;

    @Autowired
    private CardService cardService;

    @Autowired
    private TaskRecordService taskRecordService;
    /**
     * 根据标签和条件/日期查询出父任务
     * @param taskStoreQuery
     * @return
     */
    @Override
    public Result getTaskStoreByLabel(TaskStoreQuery taskStoreQuery) {

        List<Label> reList=new ArrayList<>();

        Wrapper<Label> labelwr=new EntityWrapper<>();
        List<Label> labels = labelService.selectList(labelwr);

        if(CollectionUtils.isEmpty(labels)){
            return  Result.success();
        }
        List<Label> yesLabes=new ArrayList<>();//处于当前时间范围内的标签
        List<Label> noLabes=new ArrayList<>();//不处于当前时间范围内的标签

        //判断现在的时间，把属于这个时间段的习惯筛选出来
        String nowTime = DateFormatUtils.format(new Date(), "HHmm");//2018
        String time1 = nowTime.substring(0,2);//现在几点
        String time2 = nowTime.substring(2,4);//现在多少分
        Integer num1 = Integer.valueOf(time1);

        for (Label label : labels) {
            String executeTime = label.getExecuteTime();
            if(!StringUtils.isEmpty(executeTime)){
                //判断是否处于当前时间
                List<Integer> integers = JSONArray.parseArray(executeTime, Integer.class);
                if(integers.get(num1)==2){
                    yesLabes.add(label);
                }else{
                    noLabes.add(label);
                }
            }else{
                noLabes.add(label);
            }
        }
        this.processorList(yesLabes, taskStoreQuery);
        this.processorList(noLabes, taskStoreQuery);

        if(!CollectionUtils.isEmpty(yesLabes)){
            List<Label> hsdListIsCollect = yesLabes.stream().sorted(Comparator.comparing(Label::getPriority).reversed()).collect(Collectors.toList());
            reList.addAll(hsdListIsCollect);
        }
        if(!CollectionUtils.isEmpty(noLabes)){
            List<Label> hsdListNoCollect = noLabes.stream().sorted(Comparator.comparing(Label::getPriority).reversed()).collect(Collectors.toList());
            reList.addAll(hsdListNoCollect);
        }
        return Result.success(reList);
    }

    @Override
    public Result getSubTaskList(TaskStoreQuery taskStoreQuery) {



        Integer parentId = taskStoreQuery.getParentId();
        Wrapper<TaskStore> wr=new EntityWrapper<>();
        wr.eq("parent_id",parentId);
        List<TaskStore> taskStores = this.selectList(wr);
        if(!CollectionUtils.isEmpty(taskStores)){
            for (TaskStore taskStore : taskStores) {
                String cardId = taskStore.getCardId();
                if(!StringUtils.isEmpty(cardId)){
                    List<Integer> integers = JSON.parseArray(cardId, Integer.class);
                    Wrapper<Card> wri=new EntityWrapper<>();
                    wri.in("id",integers);
                    List<Card> cards = cardService.selectList(wri);

                    //如果有的卡片不存在了
                    List<Integer> cardIdStr=new ArrayList<>();
                    if(!CollectionUtils.isEmpty(cards)){
                        taskStore.setCardList(cards);

                        for (Card card : cards) {
                            Integer id = card.getId();
                            cardIdStr.add(id);
                        }
                    }
                    if(!CollectionUtils.isEmpty(cardIdStr)){
                        String s = JSONArray.toJSONString(cardIdStr);
                        taskStore.setCardId(s);
                    }
                }
            }

            this.updateBatchById(taskStores);
        }
        return Result.success(taskStores);
    }

    public void processorList(List<Label> yesLabes,TaskStoreQuery taskStoreQuery){
        if(!CollectionUtils.isEmpty(yesLabes)){
            //根据标签查询父任务
            for (Label yesLabe : yesLabes) {
                Integer id = yesLabe.getId();
                Wrapper<TaskStore> taskStoreWr=new EntityWrapper<>();
                taskStoreWr.eq("label_id",id);
                List<TaskStore> taskStores = this.selectList(taskStoreWr);

                List<TaskRecord> taskRecords=new ArrayList<>();
                if(!CollectionUtils.isEmpty(taskStores)){
                    yesLabe.setTaskStoreList(taskStores);
                    for (TaskStore taskStore : taskStores) {
                        //查询出卡片
                        String cardId = taskStore.getCardId();

                        if(!StringUtils.isEmpty(cardId)){
                            List<String> strings = JSONArray.parseArray(cardId, String.class);
                            Wrapper<Card> wrCard =new EntityWrapper<>();
                            wrCard.in("id",strings);
                            List<Card> cards = cardService.selectList(wrCard);
                            List<Integer> cardIds=new ArrayList<>();
                            if(!CollectionUtils.isEmpty(cards)){
                                for (Card card : cards) {
                                    cardIds.add(card.getId());
                                }
                                String cardsIdJson = JSONArray.toJSONString(cardIds);
                                taskStore.setCardId(cardsIdJson);
                                this.updateById(taskStore);
                                taskStore.setCardList(cards);
                            }
                        }

                        //查村出任务记录
                        Integer createTime = taskStoreQuery.getCreateTime();

                        Wrapper<TaskRecord> wr=new EntityWrapper<>();
                        wr.eq("add_time", DateUtil.getDate_yyyyMMdd());
                        wr.eq("task_id",taskStore.getId());
                        TaskRecord taskRecord = taskRecordService.selectOne(wr);
                        if(null!=taskRecord){
                            taskStore.setTaskRecord(taskRecord);
                        }else{
                            TaskRecord trd=new TaskRecord();
                            trd.setTaskId(taskStore.getId());
                            trd.setAddTime(DateUtil.getDate_yyyyMMdd());
                            taskRecords.add(trd);
                        }
                    }

                    if(!CollectionUtils.isEmpty(taskRecords)){
                        boolean flag = taskRecordService.insertBatch(taskRecords);
                        if(flag){
                            for (TaskStore taskStore : taskStores) {
                                for (TaskRecord taskRecord : taskRecords) {
                                    if(taskRecord.getTaskId()==taskStore.getId()){
                                        taskStore.setTaskRecord(taskRecord);
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }

//    @Autowired
//    private HabitStoreService habitStoreService;
//
//    @Autowired
//    private TaskStoreDetailService taskStoreDetailService;
//
//    /**
//     * 根据时间获取当日任务列表以及数据
//     * @param data
//     * @return
//     */
//    @Override
//    public Result getTaskStoreList(String data) {
//
//        //查询开启的习惯
//        Wrapper<HabitStore> wr =new EntityWrapper<>();
//        List<HabitStore> habitStores = habitStoreService.selectList(wr);
//        if(CollectionUtils.isEmpty(habitStores)){
//            return null;
//        }
//
//        List<TaskStore> taskStoreList=new ArrayList<>();
//        for (HabitStore habitStore : habitStores) {
//            Wrapper<TaskStore> taskWr =new EntityWrapper<>();
//            taskWr.eq("habit_store_id",habitStore.getId());
//            List<TaskStore> taskStores = this.selectList(taskWr);
//            taskStoreList.addAll(taskStores);
//        }
//
//        if(!CollectionUtils.isEmpty(taskStoreList)){
//            return null;
//        }
//
//        List<TaskStoreDetail> taskStoreDetails=new ArrayList<>();
//        //根据当前时间查询是否有任务，否者创建一条当日的新数据。如果当天日期不等于当前日期，则返回一条空数据
//        for (TaskStore taskStore : taskStoreList) {
//            Wrapper<TaskStoreDetail> tsdWr =new EntityWrapper<>();
//            tsdWr.eq("task_id",taskStore.getId());
//            tsdWr.eq("create_time","2021-01-12");
//            TaskStoreDetail taskStoreDetail = taskStoreDetailService.selectOne(tsdWr);
//            if(null==taskStoreDetail){
//                TaskStoreDetail tsd=new TaskStoreDetail();
//                tsd.setCreateTime("2021-01-12");
//                tsd.setTaskId(taskStore.getId());
//                taskStoreDetailService.insert(tsd);
//                taskStoreDetails.add(tsd);
//            }else{
//                taskStoreDetails.add(taskStoreDetail);  //添加到当前习惯下
//            }
//        }
//        return null;
//    }
//
//    /**
//     * 根据任务id获取子任务
//     */
//    @Override
//    public Result getChildrenList(Integer id) {
//        Wrapper<TaskStore> wr =new EntityWrapper<>();
//        wr.eq("parent_id",id);
//        List<TaskStore> taskStores = this.selectList(wr);
//        return Result.success(taskStores);
//    }
//
//    /**
//     * 查询出习惯下的任务
//     * @return
//     */
//    @Override
//    public Result getTaskByHabit() {
//        //查询出所有习惯
//        Wrapper<HabitStore> wr =new EntityWrapper<>();
//        List<HabitStore> habitStores = habitStoreService.selectList(wr);
//        if(CollectionUtils.isEmpty(habitStores)){
//           return  null;
//        }
//
//        List<Integer> habitId=new ArrayList<>();
//        for (HabitStore habitStore : habitStores) {
//            habitId.add(habitStore.getId());
//        }
//
//        Wrapper<TaskStore> taskWr =new EntityWrapper<>();
//        taskWr.in("habit_store_id",habitId);
//        List<TaskStore> taskStores = this.selectList(taskWr);
//
//        if(CollectionUtils.isEmpty(taskStores)){
//            return  null;
//        }
//        return Result.success(taskStores);
//    }
}
